package com.liuqi.voicenotes.ui

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.speech.RecognizerIntent
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.AssistChip
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp

@Composable
fun VoiceChatOverlay(
    processing: Boolean,
    onFinalText: (String) -> Unit,
    onDismiss: () -> Unit
) {
    val context = LocalContext.current

    fun findPreferredRecognitionService(ctx: Context): android.content.ComponentName? {
        return try {
            val pm = ctx.packageManager
            val intent = Intent(android.speech.RecognitionService.SERVICE_INTERFACE)
            val services = pm.queryIntentServices(intent, PackageManager.MATCH_DEFAULT_ONLY)
            // 优先顺序：Xiaomi/MI Brain -> MIUI -> Google QuickSearchBox -> iFlytek -> 系统服务 -> 任意
            val target = services?.firstOrNull { si ->
                val p = si.serviceInfo.packageName.lowercase()
                val n = si.serviceInfo.name.lowercase()
                p.contains("xiaomi") || p.contains("mibrain") || n.contains("mibrain")
            }
                ?: services?.firstOrNull { it.serviceInfo.packageName.contains("miui", true) }
                ?: services?.firstOrNull { si ->
                    val p = si.serviceInfo.packageName.lowercase()
                    p.contains("googlequicksearchbox") || p.contains("quicksearchbox")
                }
                ?: services?.firstOrNull { it.serviceInfo.packageName.contains("iflytek", true) }
                ?: services?.firstOrNull { (it.serviceInfo.applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_SYSTEM) != 0 }
                ?: services?.firstOrNull()
            target?.let { android.content.ComponentName(it.serviceInfo.packageName, it.serviceInfo.name) }
        } catch (e: Exception) {
            null
        }
    }

    val serviceComponent = remember { findPreferredRecognitionService(context) }
    val recognizer = remember {
        try {
            if (serviceComponent != null) {
                android.speech.SpeechRecognizer.createSpeechRecognizer(context, serviceComponent)
            } else {
                android.speech.SpeechRecognizer.createSpeechRecognizer(context)
            }
        } catch (e: Exception) {
            android.speech.SpeechRecognizer.createSpeechRecognizer(context)
        }
    }

    var isListening by remember { mutableStateOf(false) }
    var lastPartialText by remember { mutableStateOf<String?>(null) }
    var finalDispatched by remember { mutableStateOf(false) }
    var anyCallbackReceived by remember { mutableStateOf(false) }

    // 设置识别监听器并确保服务可用
    DisposableEffect(Unit) {
        val available = android.speech.SpeechRecognizer.isRecognitionAvailable(context)
        if (!available) {
            onDismiss()
            return@DisposableEffect onDispose { }
        }
        recognizer.setRecognitionListener(object : android.speech.RecognitionListener {
            override fun onReadyForSpeech(params: Bundle?) { anyCallbackReceived = true }
            override fun onBeginningOfSpeech() { anyCallbackReceived = true }
            override fun onRmsChanged(rmsdB: Float) { }
            override fun onBufferReceived(buffer: ByteArray?) { }
            override fun onEndOfSpeech() { anyCallbackReceived = true }
            override fun onError(error: Int) {
                anyCallbackReceived = true
                if (!finalDispatched) {
                    finalDispatched = true
                    onFinalText(lastPartialText ?: "")
                }
            }
            override fun onPartialResults(partialResults: Bundle?) {
                anyCallbackReceived = true
                val list = partialResults?.getStringArrayList(android.speech.SpeechRecognizer.RESULTS_RECOGNITION)
                val first = list?.firstOrNull()
                lastPartialText = first
            }
            override fun onEvent(eventType: Int, params: Bundle?) { anyCallbackReceived = true }
            override fun onResults(results: Bundle?) {
                anyCallbackReceived = true
                val list = results?.getStringArrayList(android.speech.SpeechRecognizer.RESULTS_RECOGNITION)
                val first = list?.firstOrNull()
                if (!finalDispatched) {
                    finalDispatched = true
                    onFinalText(first ?: lastPartialText ?: "")
                }
            }
        })
        onDispose {
            try { recognizer.stopListening() } catch (_: Exception) {}
            try { recognizer.cancel() } catch (_: Exception) {}
            try { recognizer.destroy() } catch (_: Exception) {}
        }
    }
    fun stopListening() {
        // 某些引擎需要一点点延迟再停止，避免丢回调
        isListening = false
        android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
            try {
                recognizer.stopListening()
            } catch (_: Exception) {}
        }, 300)
        // 兜底：若1.2秒内没有收到 onResults，则用最后的部分结果（允许为空字符串）
        android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
            if (!finalDispatched) {
                finalDispatched = true
                onFinalText(lastPartialText ?: "")
            }
        }, 1200)
    }
    fun startListening() {
        if (isListening) return
        val langTag = try { java.util.Locale.getDefault().toLanguageTag() } catch (_: Throwable) { "zh-CN" }
        val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
            putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
            putExtra(RecognizerIntent.EXTRA_LANGUAGE, langTag)
            putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
            putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1)
            putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, context.packageName)
            putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, false)
            putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, 600)
            putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS, 600)
            putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 1200)
            putExtra(RecognizerIntent.EXTRA_PROMPT, "请说话…")
        }
        isListening = true
        anyCallbackReceived = false
        android.os.Handler(android.os.Looper.getMainLooper()).post {
            try {
                recognizer.startListening(intent)
            } catch (e: Exception) {
                isListening = false
            }
        }
        // 看门狗：如果 2.5s 内完全没有任何回调，主动 stop 并用部分结果兜底
        android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
            if (isListening && !anyCallbackReceived) {
                stopListening()
            }
        }, 2500)
    }

    // UI：黑色背景 + 中间大圆，按住说话
    androidx.compose.foundation.layout.Box(
        modifier = Modifier
            .fillMaxSize()
            .background(androidx.compose.ui.graphics.Color.Black)
    ) {
        // 中间圆形按钮：按下开始，松开结束
        androidx.compose.foundation.layout.Box(
            modifier = Modifier
                .align(Alignment.Center)
                .size(200.dp)
                .background(
                    brush = androidx.compose.ui.graphics.Brush.radialGradient(
                        colors = listOf(
                            androidx.compose.ui.graphics.Color(0xFF7FC8FF),
                            androidx.compose.ui.graphics.Color(0xFFBEE3FF)
                        )
                    ),
                    shape = androidx.compose.foundation.shape.CircleShape
                )
                .pointerInput(processing) {
                    if (!processing) {
                        detectTapGestures(
                            onPress = {
                                startListening()
                                try {
                                    tryAwaitRelease()
                                } finally {
                                    stopListening()
                                }
                            }
                        )
                    }
                },
        ) {}

        // 解析中：中央显示进度圈
        if (processing) {
            androidx.compose.material3.CircularProgressIndicator(
                modifier = Modifier.align(Alignment.Center),
                color = androidx.compose.ui.graphics.Color.White
            )
        }

        // 左下角提示
        Text(
            text = if (isListening) "正在听…松开结束" else if (processing) "正在解析…请稍候" else "按住说话",
            color = androidx.compose.ui.graphics.Color.White,
            modifier = Modifier
                .align(Alignment.BottomStart)
                .padding(24.dp)
        )

        // 右下角关闭按钮
        AssistChip(
            onClick = { if (!processing) onDismiss() },
            label = { Text(if (processing) "解析中…" else "关闭", color = androidx.compose.ui.graphics.Color.White) },
            modifier = Modifier
                .align(Alignment.BottomEnd)
                .padding(24.dp)
        )
    }
}